"""
A class to exercise the JT core functions.
"""
import itk
import vtk
import JT
import Calibration
from numpy import array

def Test():
    """
    Test the image overlay function of the image canvas class
    """
    #fixedFileName = 'C:/Lib/JointTrack/branches/bryan/Images/MovingImage.png'

    inputFixedFileName = 'C:/Users/bryan/bryan-code/2D3D/vert1/fluoro/ushortim080-LAT.mha'
    inputVolFileName = 'C:/Users/bryan/bryan-code/2D3D/vert1/CT/ucharCTv1r1.mha'
    staFile = 'C:/Users/bryan/bryan-code/2D3D/vert1/CT/ucharCTv1r1.sta'
    calFileLat = 'C:/Users/bryan/bryan-code/trunk/TestData/ext_cal1.txt'

    overlayOutputFileName = 'C:/Users/bryan/bryan-code/trunk/Tests/Test_ImageOverlayComb.mhd'
    fixedOutputFileName = 'C:/Users/bryan/bryan-code/trunk/Tests/Test_ImageOverlayFixed.mhd'
    movingOutputFileName = 'C:/Users/bryan/bryan-code/trunk/Tests/Test_ImageOverlayMoving.mhd'

    #
    # Generate Lateral Projection
    #%###########################
    xraycamLat = JT.XRayCamera()
    drrLat = JT.DRR()
    calLat = Calibration.ExternalCalibration()

    calLat.LoadConsolidatedCalibration(calFileLat)
    calLat.LoadStaFile(staFile)
    drrLat.SetXRayCamera(xraycamLat)
    drrLat.SetVolumeFilename(inputVolFileName)

    #Automatic calibration
    xraycamLat.SetExternalCalibration(calLat)

    vtkMatrixLAT = calLat.ConvertNumpyToVTKArray(calLat._VolumeT)
    drrLat.SetVolumeUserMatrix(vtkMatrixLAT)
    drrLat.SetBlackOnWhiteImage()

    #drrLat.Render()

    #
    # Prepare the image canvas
    #%###########################
    ic = JT.ImageCanvas()
    ic.SetFileName(inputFixedFileName)

    #
    # Prepare ITK components
    #%###########################
    inputImage = itk.Image.F2.New()
    outputImage = itk.Image.F2.New()

    FixedWriter = itk.ImageFileWriter[outputImage].New()
    MovingWriter = itk.ImageFileWriter[outputImage].New()

    FixedNorm = itk.NormalizeImageFilter[inputImage,inputImage].New()
    MovingNorm = itk.NormalizeImageFilter[inputImage,inputImage].New()

    FixedNorm.SetInput(ic.GetImage('itk'))

    MovingNorm.SetInput(drrLat.GetImage('itk'))

    FixedWriter.SetFileName(fixedOutputFileName)
    MovingWriter.SetFileName(movingOutputFileName)

    FixedWriter.SetInput(FixedNorm.GetOutput())
    MovingWriter.SetInput(MovingNorm.GetOutput())

    #FixedWriter.SetInput(ic.GetImage('itk'))
    #MovingWriter.SetInput(drrLat.GetImage('itk'))

    FixedWriter.Write()
    MovingWriter.Write()

    #
    # Overlay DRR image and fixed fluoro image
    #%###########################
    ic.OverlayImages(ic.GetImage('itk'),drrLat.GetImage('itk'),overlayOutputFileName)

    #Compare Fixed and Moving Images
    import ImageCompare

    #return 0 if they match, 1 otherwise.
    comp1 = ImageCompare.compare(fixedOutputFileName,movingOutputFileName)


    #Test for positive match
    assert comp1==0

    if comp1==0:
        print "Test Success!"
    else:
        print "Test Failure!"


if __name__ == "__main__":
    Test()